<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>热依木开发的贪吃蛇游戏</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4CAF50',
                        secondary: '#FFC107',
                        danger: '#F44336',
                        dark: '#212121',
                        light: '#F5F5F5',
                        easy: '#4CAF50',
                        medium: '#FFC107',
                        hard: '#F44336'
                    },
                    fontFamily: {
                        game: ['"Press Start 2P"', 'cursive']
                    }
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .game-container {
                @apply relative bg-dark rounded-lg shadow-lg overflow-hidden;
            }
            .snake {
                @apply absolute bg-primary rounded-sm;
            }
            .food {
                @apply absolute bg-secondary rounded-full;
            }
            .btn-game {
                @apply px-6 py-3 bg-primary hover:bg-primary/80 text-white font-bold rounded-lg transition-all duration-200 transform hover:scale-105 active:scale-95 focus:outline-none focus:ring-2 focus:ring-primary/50;
            }
            .btn-game-secondary {
                @apply px-4 py-2 bg-secondary hover:bg-secondary/80 text-dark font-bold rounded-lg transition-all duration-200;
            }
            .btn-difficulty {
                @apply px-6 py-4 font-bold rounded-lg transition-all duration-200 transform hover:scale-105 active:scale-95 focus:outline-none focus:ring-2;
            }
            .btn-easy {
                @apply bg-easy hover:bg-easy/80 text-white focus:ring-easy/50;
            }
            .btn-medium {
                @apply bg-medium hover:bg-medium/80 text-dark focus:ring-medium/50;
            }
            .btn-hard {
                @apply bg-hard hover:bg-hard/80 text-white focus:ring-hard/50;
            }
            .difficulty-selected {
                @apply ring-4 ring-white scale-105;
            }
            .speed-control {
                @apply flex items-center space-x-2 bg-gray-800/50 p-3 rounded-lg;
            }
            .speed-label {
                @apply text-white font-medium;
            }
            .speed-value {
                @apply text-primary font-bold w-10 text-center;
            }
            .slider {
                @apply h-2 w-full bg-gray-700 rounded-lg appearance-none cursor-pointer;
            }
            .slider::-webkit-slider-thumb {
                @apply appearance-none w-5 h-5 bg-primary rounded-full cursor-pointer;
            }
            .mobile-btn {
                @apply bg-gray-700/80 hover:bg-gray-600/80 text-white p-4 rounded-full shadow-lg active:bg-gray-500/80 transition-all duration-150;
            }
            .touch-control {
                @apply flex flex-col items-center justify-center gap-2;
            }
            .touch-control-row {
                @apply flex gap-2;
            }
        }
    </style>
    
    <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap" rel="stylesheet">
</head>
<body class="bg-gradient-to-br from-gray-800 to-gray-900 min-h-screen flex flex-col items-center justify-center p-4 font-sans overflow-hidden">
    <div class="w-full max-w-4xl flex-1 flex flex-col">
        <!-- 作者信息 -->
        <div class="text-center mb-4">
            <p class="text-gray-400 text-lg">热依木开发的贪吃蛇游戏</p>
        </div>
        
        <!-- 游戏标题 -->
        <div class="text-center mb-6">
            <h1 class="text-[clamp(1.8rem,5vw,3.5rem)] font-game text-primary mb-2 tracking-wider">贪吃蛇</h1>
            <p class="text-gray-300 text-lg">控制蛇吃食物，不要撞到墙壁或自己的身体</p>
        </div>
        
        <!-- 难度选择面板 -->
        <div id="difficultyPanel" class="mb-4 bg-gray-800/50 p-4 rounded-lg flex-1 flex flex-col">
            <h2 class="text-xl font-bold text-white mb-4 text-center">选择游戏难度</h2>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-3 flex-1">
                <div class="difficulty-option">
                    <button id="easyBtn" class="btn-difficulty btn-easy w-full difficulty-selected py-3">
                        <i class="fa fa-check-circle mr-2"></i>初级
                    </button>
                    <div class="mt-2 bg-gray-700/50 p-2 rounded-lg flex-1">
                        <ul class="text-gray-300 text-sm space-y-1">
                            <li><i class="fa fa-tachometer text-easy mr-1"></i> 初始速度: 3</li>
                            <li><i class="fa fa-bolt text-easy mr-1"></i> 速度增长: 慢</li>
                            <li><i class="fa fa-shield text-easy mr-1"></i> 安全区域: 大</li>
                            <li><i class="fa fa-star text-easy mr-1"></i> 分数奖励: 10分/食物</li>
                        </ul>
                    </div>
                </div>
                
                <div class="difficulty-option">
                    <button id="mediumBtn" class="btn-difficulty btn-medium w-full py-3">
                        <i class="fa fa-check-circle mr-2 hidden"></i>中级
                    </button>
                    <div class="mt-2 bg-gray-700/50 p-2 rounded-lg flex-1">
                        <ul class="text-gray-300 text-sm space-y-1">
                            <li><i class="fa fa-tachometer text-medium mr-1"></i> 初始速度: 5</li>
                            <li><i class="fa fa-bolt text-medium mr-1"></i> 速度增长: 中等</li>
                            <li><i class="fa fa-shield text-medium mr-1"></i> 安全区域: 中等</li>
                            <li><i class="fa fa-star text-medium mr-1"></i> 分数奖励: 15分/食物</li>
                        </ul>
                    </div>
                </div>
                
                <div class="difficulty-option">
                    <button id="hardBtn" class="btn-difficulty btn-hard w-full py-3">
                        <i class="fa fa-check-circle mr-2 hidden"></i>高级
                    </button>
                    <div class="mt-2 bg-gray-700/50 p-2 rounded-lg flex-1">
                        <ul class="text-gray-300 text-sm space-y-1">
                            <li><i class="fa fa-tachometer text-hard mr-1"></i> 初始速度: 8</li>
                            <li><i class="fa fa-bolt text-hard mr-1"></i> 速度增长: 快</li>
                            <li><i class="fa fa-shield text-hard mr-1"></i> 安全区域: 小</li>
                            <li><i class="fa fa-star text-hard mr-1"></i> 分数奖励: 25分/食物</li>
                        </ul>
                    </div>
                </div>
            </div>
            
            <div class="mt-4 text-center">
                <button id="startGameBtn" class="btn-game py-2 w-full sm:w-auto">
                    <i class="fa fa-play mr-2"></i>开始游戏
                </button>
            </div>
        </div>
        
        <!-- 游戏控制面板 -->
        <div id="gameControlPanel" class="flex flex-wrap justify-between items-center mb-2 bg-gray-800/50 p-3 rounded-lg hidden">
            <div class="flex flex-wrap gap-3 w-full sm:w-auto">
                <div class="flex items-center text-white">
                    <i class="fa fa-star text-secondary mr-2"></i>
                    <span class="font-bold text-lg">分数: <span id="score" class="text-primary">0</span></span>
                </div>
                <div class="flex items-center text-white">
                    <i class="fa fa-trophy text-yellow-400 mr-2"></i>
                    <span class="font-bold text-lg">最高分: <span id="highScore" class="text-yellow-400">0</span></span>
                </div>
                <div class="flex items-center text-white">
                    <i class="fa fa-flag text-blue-400 mr-2"></i>
                    <span class="font-bold text-lg">难度: <span id="currentDifficulty" class="text-blue-400">初级</span></span>
                </div>
            </div>
            
            <!-- 速度控制 -->
            <div class="speed-control w-full sm:w-auto mt-3 sm:mt-0 p-2">
                <label for="speedSlider" class="speed-label text-sm">速度:</label>
                <input type="range" id="speedSlider" min="1" max="10" value="3" class="slider">
                <span id="speedValue" class="speed-value">3</span>
            </div>
            
            <div class="flex flex-wrap gap-2 mt-3 w-full sm:w-auto">
                <button id="pauseBtn" class="btn-game-secondary py-2 px-3" disabled>
                    <i class="fa fa-pause mr-1"></i>暂停
                </button>
                <button id="restartBtn" class="btn-game-secondary py-2 px-3" disabled>
                    <i class="fa fa-refresh mr-1"></i>重新开始
                </button>
                <!-- 添加返回按钮 -->
                <button id="backBtn" class="btn-game-secondary py-2 px-3" disabled>
                    <i class="fa fa-arrow-left mr-1"></i>返回
                </button>
            </div>
        </div>
        
        <!-- 游戏区域 -->
        <div id="gameArea" class="game-container w-full aspect-[4/3] sm:aspect-[21/9] hidden flex-1">
            <canvas id="gameCanvas" class="w-full h-full"></canvas>
            
            <!-- 游戏结束遮罩 -->
            <div id="gameOver" class="absolute inset-0 bg-dark/80 flex flex-col items-center justify-center hidden">
                <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-game text-danger mb-6">游戏结束!</h2>
                <p class="text-white text-xl mb-2">你的分数: <span id="finalScore" class="text-primary font-bold">0</span></p>
                <p class="text-gray-300 mb-8">难度: <span id="endDifficulty" class="text-blue-400">初级</span></p>
                <div class="flex flex-wrap gap-3 justify-center">
                    <button id="playAgainBtn" class="btn-game">
                        <i class="fa fa-refresh mr-2"></i>再玩一次
                    </button>
                    <!-- 游戏结束时的返回按钮 -->
                    <button id="backFromGameOverBtn" class="btn-game-secondary">
                        <i class="fa fa-arrow-left mr-2"></i>返回
                    </button>
                </div>
            </div>
            
            <!-- 加载中遮罩 -->
            <div id="loadingScreen" class="absolute inset-0 bg-dark/90 flex flex-col items-center justify-center">
                <div class="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-primary mb-4"></div>
                <h2 class="text-2xl font-game text-primary mb-2">加载中...</h2>
                <p class="text-gray-300">准备游戏环境</p>
            </div>
        </div>
        
        <!-- 移动端控制按钮 -->
        <div class="mt-4 grid grid-cols-1 gap-4 max-w-md mx-auto sm:hidden hidden" id="mobileControls">
            <!-- 移动端触摸控制 -->
            <div class="touch-control">
                <div class="touch-control-row justify-center">
                    <button id="btnUp" class="mobile-btn">
                        <i class="fa fa-arrow-up text-2xl"></i>
                    </button>
                </div>
                <div class="touch-control-row justify-center">
                    <button id="btnLeft" class="mobile-btn">
                        <i class="fa fa-arrow-left text-2xl"></i>
                    </button>
                    <div class="w-4"></div>
                    <button id="btnRight" class="mobile-btn">
                        <i class="fa fa-arrow-right text-2xl"></i>
                    </button>
                </div>
                <div class="touch-control-row justify-center">
                    <button id="btnDown" class="mobile-btn">
                        <i class="fa fa-arrow-down text-2xl"></i>
                    </button>
                </div>
            </div>
            
            <!-- 游戏控制按钮 -->
            <div class="flex justify-between">
                <button id="mobilePauseBtn" class="btn-game-secondary py-3 px-4">
                    <i class="fa fa-pause mr-1"></i>暂停
                </button>
                <button id="mobileRestartBtn" class="btn-game-secondary py-3 px-4">
                    <i class="fa fa-refresh mr-1"></i>重新开始
                </button>
            </div>
        </div>
        
        <!-- 游戏说明 -->
        <div class="mt-4 bg-gray-800/50 p-4 rounded-lg hidden md:block">
            <h3 class="text-xl font-bold text-white mb-3">游戏说明</h3>
            <ul class="text-gray-300 space-y-2">
                <li class="flex items-start">
                    <i class="fa fa-keyboard-o mt-1 mr-2 text-primary"></i>
                    <span>使用方向键（↑↓←→）或WASD键控制蛇的移动方向</span>
                </li>
                <li class="flex items-start">
                    <i class="fa fa-apple mt-1 mr-2 text-secondary"></i>
                    <span>吃到食物（黄色方块）后，蛇会变长并获得分数</span>
                </li>
                <li class="flex items-start">
                    <i class="fa fa-exclamation-triangle mt-1 mr-2 text-danger"></i>
                    <span>撞到墙壁或自己的身体，游戏结束</span>
                </li>
                <li class="flex items-start">
                    <i class="fa fa-tachometer mt-1 mr-2 text-blue-400"></i>
                    <span>使用滑块调整游戏速度（1-10）或使用+/-键</span>
                </li>
                <li class="flex items-start">
                    <i class="fa fa-space-shuttle mt-1 mr-2 text-primary"></i>
                    <span>空格键暂停/继续游戏，R键重新开始，B键返回主菜单</span>
                </li>
            </ul>
        </div>
    </div>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 获取游戏元素
            const canvas = document.getElementById('gameCanvas');
            const ctx = canvas.getContext('2d');
            const scoreDisplay = document.getElementById('score');
            const highScoreDisplay = document.getElementById('highScore');
            const finalScoreDisplay = document.getElementById('finalScore');
            const pauseBtn = document.getElementById('pauseBtn');
            const restartBtn = document.getElementById('restartBtn');
            const playAgainBtn = document.getElementById('playAgainBtn');
            const gameOverScreen = document.getElementById('gameOver');
            const currentDifficultyDisplay = document.getElementById('currentDifficulty');
            const endDifficultyDisplay = document.getElementById('endDifficulty');
            const loadingScreen = document.getElementById('loadingScreen');
            
            // 获取难度选择元素
            const difficultyPanel = document.getElementById('difficultyPanel');
            const gameControlPanel = document.getElementById('gameControlPanel');
            const gameArea = document.getElementById('gameArea');
            const mobileControls = document.getElementById('mobileControls');
            const easyBtn = document.getElementById('easyBtn');
            const mediumBtn = document.getElementById('mediumBtn');
            const hardBtn = document.getElementById('hardBtn');
            const startGameBtn = document.getElementById('startGameBtn');
            
            // 获取速度控制元素
            const speedSlider = document.getElementById('speedSlider');
            const speedValue = document.getElementById('speedValue');
            
            // 获取移动端控制按钮
            const btnUp = document.getElementById('btnUp');
            const btnDown = document.getElementById('btnDown');
            const btnLeft = document.getElementById('btnLeft');
            const btnRight = document.getElementById('btnRight');
            
            // 获取移动端游戏控制按钮
            const mobilePauseBtn = document.getElementById('mobilePauseBtn');
            const mobileRestartBtn = document.getElementById('mobileRestartBtn');
            
            // 获取新增的返回按钮
            const backBtn = document.getElementById('backBtn');
            const backFromGameOverBtn = document.getElementById('backFromGameOverBtn');
            
            // 难度设置
            const difficulties = {
                easy: {
                    name: '初级',
                    color: 'text-easy',
                    initialSpeed: 3,
                    speedIncreaseRate: 0.1,
                    foodScore: 10,
                    safeZone: 0.2
                },
                medium: {
                    name: '中级',
                    color: 'text-medium',
                    initialSpeed: 5,
                    speedIncreaseRate: 0.2,
                    foodScore: 15,
                    safeZone: 0.1
                },
                hard: {
                    name: '高级',
                    color: 'text-hard',
                    initialSpeed: 8,
                    speedIncreaseRate: 0.3,
                    foodScore: 25,
                    safeZone: 0
                }
            };
            
            // 当前选择的难度
            let currentDifficulty = 'easy';
            
            // 游戏配置
            let gameConfig = {
                cellSize: 20,
                speed: difficulties[currentDifficulty].initialSpeed,
                score: 0,
                highScore: localStorage.getItem('snakeHighScore') || 0,
                direction: 'right',
                nextDirection: 'right',
                gameInterval: null,
                isPaused: false,
                isGameOver: false,
                snakeLength: 0,
                foodEaten: 0,
                lastFrameTime: 0,
                animationFrameId: null,
                touchStartX: 0,
                touchStartY: 0,
                touchEndX: 0,
                touchEndY: 0
            };
            
            // 游戏对象
            let snake = [{x: 10, y: 10}];
            let food = {};
            let gridSize = {
                width: 0,
                height: 0
            };
            
            // 更新高分显示
            highScoreDisplay.textContent = gameConfig.highScore;
            
            // 难度选择按钮点击事件
            easyBtn.addEventListener('click', function() {
                selectDifficulty('easy');
            });
            
            mediumBtn.addEventListener('click', function() {
                selectDifficulty('medium');
            });
            
            hardBtn.addEventListener('click', function() {
                selectDifficulty('hard');
            });
            
            // 选择难度
            function selectDifficulty(difficulty) {
                // 移除所有选中状态
                easyBtn.classList.remove('difficulty-selected');
                mediumBtn.classList.remove('difficulty-selected');
                hardBtn.classList.remove('difficulty-selected');
                
                // 隐藏所有检查图标
                easyBtn.querySelector('i.fa-check-circle').classList.add('hidden');
                mediumBtn.querySelector('i.fa-check-circle').classList.add('hidden');
                hardBtn.querySelector('i.fa-check-circle').classList.add('hidden');
                
                // 添加选中状态到当前难度
                if (difficulty === 'easy') {
                    easyBtn.classList.add('difficulty-selected');
                    easyBtn.querySelector('i.fa-check-circle').classList.remove('hidden');
                } else if (difficulty === 'medium') {
                    mediumBtn.classList.add('difficulty-selected');
                    mediumBtn.querySelector('i.fa-check-circle').classList.remove('hidden');
                } else if (difficulty === 'hard') {
                    hardBtn.classList.add('difficulty-selected');
                    hardBtn.querySelector('i.fa-check-circle').classList.remove('hidden');
                }
                
                // 更新当前难度
                currentDifficulty = difficulty;
                
                // 更新速度滑块
                speedSlider.value = difficulties[currentDifficulty].initialSpeed;
                speedValue.textContent = difficulties[currentDifficulty].initialSpeed;
            }
            
            // 开始游戏按钮点击事件
            startGameBtn.addEventListener('click', function() {
                // 显示加载屏幕
                loadingScreen.classList.remove('hidden');
                
                // 使用requestAnimationFrame在下次渲染前开始游戏
                requestAnimationFrame(() => {
                    // 更新游戏配置
                    gameConfig.speed = difficulties[currentDifficulty].initialSpeed;
                    gameConfig.score = 0;
                    gameConfig.snakeLength = 0;
                    gameConfig.foodEaten = 0;
                    
                    // 更新难度显示
                    currentDifficultyDisplay.textContent = difficulties[currentDifficulty].name;
                    currentDifficultyDisplay.className = difficulties[currentDifficulty].color;
                    
                    // 隐藏难度面板，显示游戏区域
                    difficultyPanel.classList.add('hidden');
                    gameControlPanel.classList.remove('hidden');
                    gameArea.classList.remove('hidden');
                    mobileControls.classList.remove('hidden');
                    
                    // 调整画布大小
                    resizeCanvas();
                    
                    // 初始化游戏
                    initGame();
                    
                    // 隐藏加载屏幕
                    setTimeout(() => {
                        loadingScreen.classList.add('hidden');
                    }, 300);
                });
            });
            
            // 调整画布大小
            function resizeCanvas() {
                const container = canvas.parentElement;
                const containerWidth = container.clientWidth;
                const containerHeight = container.clientHeight;
                
                // 限制画布最大尺寸
                const maxWidth = 600;
                const maxHeight = 400;
                
                // 确保画布大小是cellSize的倍数
                gridSize.width = Math.min(Math.floor(containerWidth / gameConfig.cellSize), Math.floor(maxWidth / gameConfig.cellSize));
                gridSize.height = Math.min(Math.floor(containerHeight / gameConfig.cellSize), Math.floor(maxHeight / gameConfig.cellSize));
                
                // 限制最小网格尺寸
                gridSize.width = Math.max(gridSize.width, 15);
                gridSize.height = Math.max(gridSize.height, 15);
                
                canvas.width = gridSize.width * gameConfig.cellSize;
                canvas.height = gridSize.height * gameConfig.cellSize;
                
                // 如果游戏已经开始，重绘游戏
                if (gameConfig.animationFrameId) {
                    draw();
                }
            }
            
            // 初始化游戏
            function initGame() {
                // 重置游戏状态
                gameConfig.direction = 'right';
                gameConfig.nextDirection = 'right';
                gameConfig.isPaused = false;
                gameConfig.isGameOver = false;
                
                // 重置蛇的位置
                snake = [{x: Math.floor(gridSize.width / 2), y: Math.floor(gridSize.height / 2)}];
                
                // 生成第一个食物
                createFood();
                
                // 更新显示
                scoreDisplay.textContent = gameConfig.score;
                gameOverScreen.classList.add('hidden');
                
                // 启用/禁用按钮
                pauseBtn.disabled = false;
                restartBtn.disabled = false;
                backBtn.disabled = false;
                mobilePauseBtn.disabled = false;
                mobileRestartBtn.disabled = false;
                
                // 取消之前的动画帧
                if (gameConfig.animationFrameId) {
                    cancelAnimationFrame(gameConfig.animationFrameId);
                }
                
                // 重置帧时间
                gameConfig.lastFrameTime = performance.now();
                
                // 使用requestAnimationFrame开始游戏循环
                gameLoop(performance.now());
            }
            
            // 生成食物
            function createFood() {
                let newFood;
                let onSnake;
                let inSafeZone;
                
                do {
                    onSnake = false;
                    inSafeZone = false;
                    
                    // 生成随机位置
                    newFood = {
                        x: Math.floor(Math.random() * gridSize.width),
                        y: Math.floor(Math.random() * gridSize.height)
                    };
                    
                    // 检查食物是否在蛇身上
                    for (let segment of snake) {
                        if (segment.x === newFood.x && segment.y === newFood.y) {
                            onSnake = true;
                            break;
                        }
                    }
                    
                    // 检查食物是否在安全区域（仅高级难度）
                    if (currentDifficulty === 'hard') {
                        const safeZone = Math.floor(gridSize.width * difficulties[currentDifficulty].safeZone);
                        if (newFood.x < safeZone || newFood.x >= gridSize.width - safeZone ||
                            newFood.y < safeZone || newFood.y >= gridSize.height - safeZone) {
                            inSafeZone = true;
                        }
                    }
                    
                } while (onSnake || inSafeZone);
                
                food = newFood;
            }
            
            // 更新游戏速度
            function updateGameSpeed(newSpeed) {
                // 限制最大速度为10，防止性能问题
                gameConfig.speed = Math.min(newSpeed, 10);
                speedValue.textContent = gameConfig.speed;
            }
            
            // 游戏循环 - 使用requestAnimationFrame
            function gameLoop(timestamp) {
                // 如果游戏暂停或结束，不继续循环
                if (gameConfig.isPaused || gameConfig.isGameOver) {
                    return;
                }
                
                // 计算时间差
                const deltaTime = timestamp - gameConfig.lastFrameTime;
                
                // 根据游戏速度计算每帧需要的时间
                const frameTime = 1000 / gameConfig.speed;
                
                // 如果距离上一帧的时间足够长，更新游戏状态
                if (deltaTime >= frameTime) {
                    gameConfig.lastFrameTime = timestamp;
                    
                    // 更新蛇的方向
                    gameConfig.direction = gameConfig.nextDirection;
                    
                    // 获取蛇头
                    let head = {x: snake[0].x, y: snake[0].y};
                    
                    // 根据方向移动蛇头
                    switch(gameConfig.direction) {
                        case 'up':
                            head.y--;
                            break;
                        case 'down':
                            head.y++;
                            break;
                        case 'left':
                            head.x--;
                            break;
                        case 'right':
                            head.x++;
                            break;
                    }
                    
                    // 检查碰撞
                    if (checkCollision(head)) {
                        gameOver();
                        return;
                    }
                    
                    // 将新的头部添加到蛇的前面
                    snake.unshift(head);
                    
                    // 检查是否吃到食物
                    if (head.x === food.x && head.y === food.y) {
                        // 增加分数
                        gameConfig.foodEaten++;
                        gameConfig.score += difficulties[currentDifficulty].foodScore;
                        scoreDisplay.textContent = gameConfig.score;
                        
                        // 更新高分
                        if (gameConfig.score > gameConfig.highScore) {
                            gameConfig.highScore = gameConfig.score;
                            highScoreDisplay.textContent = gameConfig.highScore;
                            localStorage.setItem('snakeHighScore', gameConfig.highScore);
                        }
                        
                        // 增加速度（根据难度）
                        if (gameConfig.foodEaten % 5 === 0) {
                            const newSpeed = Math.min(10, gameConfig.speed + difficulties[currentDifficulty].speedIncreaseRate);
                            updateGameSpeed(newSpeed);
                            speedSlider.value = newSpeed;
                        }
                        
                        // 生成新食物
                        createFood();
                    } else {
                        // 如果没有吃到食物，移除尾部
                        snake.pop();
                    }
                    
                    // 绘制游戏
                    draw();
                }
                
                // 继续游戏循环
                gameConfig.animationFrameId = requestAnimationFrame(gameLoop);
            }
            
            // 检查碰撞
            function checkCollision(head) {
                // 检查是否撞到墙壁
                if (head.x < 0 || head.x >= gridSize.width || head.y < 0 || head.y >= gridSize.height) {
                    return true;
                }
                
                // 检查是否撞到自己
                for (let i = 1; i < snake.length; i++) {
                    if (head.x === snake[i].x && head.y === snake[i].y) {
                        return true;
                    }
                }
                
                return false;
            }
            
            // 游戏结束
            function gameOver() {
                gameConfig.isGameOver = true;
                
                // 取消动画帧
                if (gameConfig.animationFrameId) {
                    cancelAnimationFrame(gameConfig.animationFrameId);
                }
                
                // 显示游戏结束屏幕
                finalScoreDisplay.textContent = gameConfig.score;
                endDifficultyDisplay.textContent = difficulties[currentDifficulty].name;
                endDifficultyDisplay.className = difficulties[currentDifficulty].color;
                gameOverScreen.classList.remove('hidden');
                
                // 启用/禁用按钮
                pauseBtn.disabled = true;
                restartBtn.disabled = false;
                backBtn.disabled = false;
                mobilePauseBtn.disabled = true;
                mobileRestartBtn.disabled = false;
            }
            
            // 绘制游戏
            function draw() {
                // 清空画布
                ctx.fillStyle = '#212121';
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                
                // 绘制蛇
                for (let i = 0; i < snake.length; i++) {
                    // 蛇头使用原始样式
                    if (i === 0) {
                        ctx.fillStyle = '#4CAF50'; // 原始蛇头颜色
                        
                        // 绘制蛇头
                        ctx.fillRect(
                            snake[i].x * gameConfig.cellSize, 
                            snake[i].y * gameConfig.cellSize, 
                            gameConfig.cellSize, 
                            gameConfig.cellSize
                        );
                        
                        // 蛇头标记 - 保持小方块样式
                        const markerSize = gameConfig.cellSize / 3;
                        const markerOffset = (gameConfig.cellSize - markerSize) / 2;
                        
                        ctx.fillStyle = '#FFEB3B'; // 黄色标记
                        
                        switch(gameConfig.direction) {
                            case 'up':
                                ctx.fillRect(
                                    snake[i].x * gameConfig.cellSize + markerOffset, 
                                    snake[i].y * gameConfig.cellSize, 
                                    markerSize, 
                                    markerSize
                                );
                                break;
                            case 'down':
                                ctx.fillRect(
                                    snake[i].x * gameConfig.cellSize + markerOffset, 
                                    snake[i].y * gameConfig.cellSize + gameConfig.cellSize - markerSize, 
                                    markerSize, 
                                    markerSize
                                );
                                break;
                            case 'left':
                                ctx.fillRect(
                                    snake[i].x * gameConfig.cellSize, 
                                    snake[i].y * gameConfig.cellSize + markerOffset, 
                                    markerSize, 
                                    markerSize
                                );
                                break;
                            case 'right':
                                ctx.fillRect(
                                    snake[i].x * gameConfig.cellSize + gameConfig.cellSize - markerSize, 
                                    snake[i].y * gameConfig.cellSize + markerOffset, 
                                    markerSize, 
                                    markerSize
                                );
                                break;
                        }
                    } else {
                        // 蛇身使用原始颜色
                        ctx.fillStyle = '#4CAF50';
                        ctx.fillRect(
                            snake[i].x * gameConfig.cellSize, 
                            snake[i].y * gameConfig.cellSize, 
                            gameConfig.cellSize, 
                            gameConfig.cellSize
                        );
                    }
                }
                
                // 绘制食物
                ctx.fillStyle = '#FFC107';
                ctx.fillRect(
                    food.x * gameConfig.cellSize, 
                    food.y * gameConfig.cellSize, 
                    gameConfig.cellSize, 
                    gameConfig.cellSize
                );
            }
            
            // 改变方向
            function changeDirection(newDirection) {
                // 防止180度转弯
                if (
                    (gameConfig.direction === 'up' && newDirection === 'down') ||
                    (gameConfig.direction === 'down' && newDirection === 'up') ||
                    (gameConfig.direction === 'left' && newDirection === 'right') ||
                    (gameConfig.direction === 'right' && newDirection === 'left')
                ) {
                    return;
                }
                
                gameConfig.nextDirection = newDirection;
            }
            
            // 键盘控制
            document.addEventListener('keydown', function(e) {
                switch(e.key) {
                    case 'ArrowUp':
                    case 'w':
                    case 'W':
                        changeDirection('up');
                        break;
                    case 'ArrowDown':
                    case 's':
                    case 'S':
                        changeDirection('down');
                        break;
                    case 'ArrowLeft':
                    case 'a':
                    case 'A':
                        changeDirection('left');
                        break;
                    case 'ArrowRight':
                    case 'd':
                    case 'D':
                        changeDirection('right');
                        break;
                    case ' ': // 空格键暂停/继续
                        togglePause();
                        break;
                    case 'r': // R键重新开始
                    case 'R':
                        if (gameConfig.isGameOver) {
                            initGame();
                        }
                        break;
                    case '+': // 加号键增加速度
                    case '=':
                        if (gameConfig.speed < 10) {
                            updateGameSpeed(gameConfig.speed + 1);
                            speedSlider.value = gameConfig.speed;
                        }
                        break;
                    case '-': // 减号键减少速度
                        if (gameConfig.speed > 1) {
                            updateGameSpeed(gameConfig.speed - 1);
                            speedSlider.value = gameConfig.speed;
                        }
                        break;
                    case 'b': // B键返回
                    case 'B':
                        goBackToMainMenu();
                        break;
                }
            });
            
            // 移动端控制按钮
            btnUp.addEventListener('touchstart', (e) => {
                e.preventDefault();
                changeDirection('up');
            });
            btnUp.addEventListener('click', () => changeDirection('up'));
            
            btnDown.addEventListener('touchstart', (e) => {
                e.preventDefault();
                changeDirection('down');
            });
            btnDown.addEventListener('click', () => changeDirection('down'));
            
            btnLeft.addEventListener('touchstart', (e) => {
                e.preventDefault();
                changeDirection('left');
            });
            btnLeft.addEventListener('click', () => changeDirection('left'));
            
            btnRight.addEventListener('touchstart', (e) => {
                e.preventDefault();
                changeDirection('right');
            });
            btnRight.addEventListener('click', () => changeDirection('right'));
            
            // 移动端游戏控制按钮
            mobilePauseBtn.addEventListener('click', togglePause);
            mobileRestartBtn.addEventListener('click', initGame);
            
            // 滑动控制
            function handleTouchStart(e) {
                gameConfig.touchStartX = e.touches[0].clientX;
                gameConfig.touchStartY = e.touches[0].clientY;
            }
            
            function handleTouchEnd(e) {
                if (!gameConfig.touchStartX || !gameConfig.touchStartY) {
                    return;
                }
                
                gameConfig.touchEndX = e.changedTouches[0].clientX;
                gameConfig.touchEndY = e.changedTouches[0].clientY;
                
                handleSwipe();
                
                // 重置触摸起点
                gameConfig.touchStartX = 0;
                gameConfig.touchStartY = 0;
            }
            
            function handleSwipe() {
                const xDiff = gameConfig.touchEndX - gameConfig.touchStartX;
                const yDiff = gameConfig.touchEndY - gameConfig.touchStartY;
                
                // 设置最小滑动距离阈值
                const threshold = 50;
                
                if (Math.abs(xDiff) > Math.abs(yDiff)) {
                    // 水平滑动
                    if (Math.abs(xDiff) > threshold) {
                        if (xDiff > 0) {
                            // 向右滑动
                            changeDirection('right');
                        } else {
                            // 向左滑动
                            changeDirection('left');
                        }
                    }
                } else {
                    // 垂直滑动
                    if (Math.abs(yDiff) > threshold) {
                        if (yDiff > 0) {
                            // 向下滑动
                            changeDirection('down');
                        } else {
                            // 向上滑动
                            changeDirection('up');
                        }
                    }
                }
            }
            
            // 添加触摸事件监听器
            canvas.addEventListener('touchstart', handleTouchStart, false);
            canvas.addEventListener('touchend', handleTouchEnd, false);
            
            // 防止触摸事件默认行为
            canvas.addEventListener('touchmove', function(e) {
                e.preventDefault();
            }, false);
            
            // 速度控制
            speedSlider.addEventListener('input', function() {
                updateGameSpeed(parseInt(this.value));
            });
            
            // 暂停/继续游戏
            function togglePause() {
                if (gameConfig.isGameOver) return;
                
                gameConfig.isPaused = !gameConfig.isPaused;
                
                if (gameConfig.isPaused) {
                    pauseBtn.innerHTML = '<i class="fa fa-play mr-2"></i>继续';
                    mobilePauseBtn.innerHTML = '<i class="fa fa-play mr-2"></i>继续';
                } else {
                    pauseBtn.innerHTML = '<i class="fa fa-pause mr-2"></i>暂停';
                    mobilePauseBtn.innerHTML = '<i class="fa fa-pause mr-2"></i>暂停';
                    gameConfig.lastFrameTime = performance.now();
                    gameLoop(performance.now());
                }
            }
            
            pauseBtn.addEventListener('click', togglePause);
            
            // 重新开始游戏
            restartBtn.addEventListener('click', initGame);
            
            // 再玩一次
            playAgainBtn.addEventListener('click', function() {
                initGame();
            });
            
            // 返回主菜单
            function goBackToMainMenu() {
                // 取消动画帧
                if (gameConfig.animationFrameId) {
                    cancelAnimationFrame(gameConfig.animationFrameId);
                }
                
                // 重置游戏状态
                gameConfig.isPaused = false;
                gameConfig.isGameOver = false;
                
                // 隐藏游戏区域，显示难度选择
                gameArea.classList.add('hidden');
                gameControlPanel.classList.add('hidden');
                mobileControls.classList.add('hidden');
                difficultyPanel.classList.remove('hidden');
                gameOverScreen.classList.add('hidden');
                
                // 重置难度选择为初级
                selectDifficulty('easy');
            }
            
            // 返回按钮点击事件
            backBtn.addEventListener('click', goBackToMainMenu);
            backFromGameOverBtn.addEventListener('click', goBackToMainMenu);
            
            // 窗口大小改变时调整画布
            window.addEventListener('resize', resizeCanvas);
            
            // 初始化画布大小
            resizeCanvas();
            
            // 初始绘制
            draw();
        });
    </script>
</body>
</html>
